package com.auth.manage.controller.user;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.auth.manage.domain.convertor.AuthorizationConvertor;
import com.auth.manage.domain.entity.AuthCode;
import com.auth.manage.domain.entity.AuthPort;
import com.auth.manage.domain.service.AuthorizationPortService;
import com.auth.manage.domain.service.AuthorizationService;
import com.auth.manage.domain.vo.AuthCodeVO;
import com.auth.manage.domain.vo.AuthIpAndPortVO;
import com.auth.manage.domain.vo.AuthPortVO;
import com.auth.manage.param.user.AuthPortUnBindParam;
import com.auth.manage.web.vo.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

// 授权码
@RequiredArgsConstructor
@RestController
@RequestMapping("/user/authCodes")
public class UserAuthorizationController {

    private final AuthorizationService authorizationService;

    private final AuthorizationPortService authorizationPortService;

    // 查询自己的授权码集合
    @GetMapping
    public Result getAuthCodes(){
        Long userId = (Long) StpUtil.getLoginId();
        List<AuthCode> list =  authorizationService.getAuthCodesByUserId(userId);
        List<AuthCodeVO> authCodeVOS = AuthorizationConvertor.INSTANCE.do2VO(list);
        return Result.success(list);
    }

    // 查询cdk对应的ip和端口：ip和端口在port表，做了cdk的冗余
    @GetMapping("/getIpAndPortsByAuthCode")
    public Result getIpAndPort(String cdk){
        List<AuthPort> authPortList = authorizationPortService.getPortsByCdk(cdk);
        AuthIpAndPortVO vo = new AuthIpAndPortVO();
        List<AuthPortVO> authPortVOS = BeanUtil.copyToList(authPortList, AuthPortVO.class);
        vo.setPortList(authPortVOS);
        BeanUtils.copyProperties(authPortList.get(0), vo);
        return Result.success(vo);
    }

    // 解绑授权码的Ip和端口
    @PutMapping
    public Result unbindIpAndPorts(@RequestBody AuthPortUnBindParam param) {
        authorizationService.unbindAuthCodes(param.getAuthCodes());
        return Result.success();
    }

}
